package com.study.quiz.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author CJunGod
 * @create 2020-03-14 19:37
 **/
@Slf4j
@Component
public class AliyunOssUtil {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.sufferUrl}")
    private String sufferUrl;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    /**
     * 获取OSS连接
     */
    public OSSClient getOssClient() {
        //创建OssClient对象
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        //判断仓库是否存在
        if (ossClient.doesBucketExist(bucketName)) {
            log.info("OSS对象创建成功，连接仓库名为:{}", bucketName);
            return ossClient;
        }

        return ossClient;
    }

    /**
     * 创建bucket 权限为公共读
     */
    public void createBucket(String bucket, OSSClient ossClient) {
        CreateBucketRequest bucketRequest = new CreateBucketRequest(null);
        bucketRequest.setBucketName(bucket);
        bucketRequest.setCannedACL(CannedAccessControlList.PublicRead);//设置权限为公共读
        ossClient.createBucket(bucketRequest);
    }

    /**
     * 上传图片
     */
    public String uploadImg(MultipartFile file) {
        //获取连接
        OSSClient ossClient = this.getOssClient();
        //获取文件后缀名称
        String substring = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //上传到OSS的哪个文件夹 通过fileName 来指定
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String format = sdf.format(new Date());
        //为了避免图片重名，使用UUID来命名图片
        String uuId = UUID.randomUUID().toString().replace("-", "");
        String fileName = uuId + "" + format + "" + "" + substring;
        String successUrl = null;
        //通过OSSClient来获取上传文件后返回的url
        try {
            ossClient.putObject(bucketName, fileName, new ByteArrayInputStream(file.getBytes()));
            successUrl = sufferUrl + fileName;
            log.info("---> 上传文件成功，文件路径为：{}", successUrl);
            // 设置URL过期时间为1小时。
            Date expiration = new Date(new Date().getTime() + 3600 * 1000 * 24 * 365 * 10);
            // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
            URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);
            return url.toString();
        } catch (Exception e) {
            log.error("上传错误", e);
        } finally {
            ossClient.shutdown();
        }

        return successUrl;
    }

}

